package cn.readjava.controller;

import cn.readjava.bean.User;
import cn.readjava.service.UserService;
import cn.readjava.shiro.LoginType;
import cn.readjava.shiro.UserToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;

@Controller
public class LoginController {

    @Resource
    private UserService userService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String login(HttpServletRequest request, User user, Model model) {
        Subject subject = SecurityUtils.getSubject();
        UserToken token = new UserToken(user.getUserEmail(), user.getUserPassword(), LoginType.USER.toString());
        model.addAttribute("user", user); // 回显数据
        try {
            subject.login(token);
            User currentUser = (User) subject.getPrincipal();
            if (currentUser.getUserState() == 1) {
                model.addAttribute("message", "该用户已被冻结");
                return "login";
            }
            currentUser.setLoginTime(new Timestamp(System.currentTimeMillis()));
            userService.save(currentUser);
            SecurityUtils.getSubject().getSession().setAttribute("currentUser", currentUser);

            SavedRequest savedRequest = WebUtils.getSavedRequest(request);
            String url = "user/info";
            if(savedRequest != null){
                url = savedRequest.getRequestUrl();
            }
            return "redirect:" + url;

        } catch (DisabledAccountException e) {
            model.addAttribute("message", "该用户未授权");
            return "login";
        } catch (UnknownAccountException e) {
            model.addAttribute("message", "该用户不存在");
            return "login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("message", "密码错误");
            return "login";
        }
    }
}
